# -*- coding: utf-8 -*-
# @Author  : Lison Song
# @Time    : 2023/3/21 10:44
from flask import Blueprint, render_template, request, session, jsonify
from flask_login import login_required, current_user
from sqlalchemy import desc, not_
from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Role, Dept
from applications.models import Weixin_articles, Weixin_Official_Acc, AdminLog
from applications.models import Robot_Info
from applications.common.appenv import HttpBaseCode
from applications.common.utils.mytools import MyTools

admin_robot = Blueprint('robot', __name__, url_prefix='/admin/robot')


# 机器人管理
@admin_robot.get('/')
@authorize("admin:robot:main")
def main():
    return render_template('admin/robot/main.html')


## 获取更多机器人采集东台
@admin_robot.get('/moreCollectData')
@authorize("admin:robot:main")
def moreCollectData():
    return render_template('admin/robot/moreCollectData.html')


## 获取全部 机器人数据 分页
@admin_robot.get('/infoAll')
@authorize("admin:robot:main")
def robot_infoAll():
    name = str_escape(request.args.get('name', type=str))
    code = str_escape(request.args.get('code', type=str))
    filters = []
    if name:
        filters.append(Robot_Info.name.contains(name))
    if code:
        filters.append(Robot_Info.code.contains(code))
    query = db.session.query(
        Robot_Info
    ).filter(*filters).order_by(
        Robot_Info.update_at.desc()).layui_paginate()

    return table_api(
        data=[{
            'id': item.id,
            'name': item.name,
            'code': item.code,
            'remark': item.remark,
            'enable': item.enable,
            'capacity': item.capacity,
            'now_capacity': getRobotNowCapacity(item.type, item.id),
            'type': getRobotTypeName(item.type),
            'create_at': item.create_at,
            'update_at': item.update_at,
            'avatar': item.avatar
        } for item in query.items],
        count=query.total)


# 获得机器人的负载量
def getRobotNowCapacity(type, id):
    if type == 'GZH':
        return Weixin_Official_Acc.query.filter_by(robot_id=id).count()
    else:
        return 0


# 获得机器人 类型名称
def getRobotTypeName(type):
    if type == 'GZH':
        return "公众号文章采集"
    else:
        return ""


## 获取全部 机器人数据 不分页
@admin_robot.get('/data')
@login_required
def robot_data():
    result = {}
    try:
        res = db.session.query(Robot_Info).filter(not_(Robot_Info.type == None)).order_by(
            Robot_Info.id.desc()).all()
        data = []
        for item in res:
            robot = {}
            robot['id'] = item.id
            robot['name'] = item.name
            robot['remark'] = item.remark
            robot['code'] = item.code
            robot['enbale'] = item.enable
            robot['create_at'] = MyTools.getDatetimestr(item.create_at)
            robot['update_at'] = MyTools.getDatetimestr(item.update_at)
            robot['now_capacity'] = getRobotNowCapacity(item.type, item.id)
            data.append(robot)
        result['data'] = data
        result['count'] = len(res)
        result['code'] = HttpBaseCode.SUCCESS_CODE
        result['message'] = HttpBaseCode.SUCCESS_MESSAGE
    except Exception as e:
        result['code'] = HttpBaseCode.FAIL_CODE
        result['message'] = HttpBaseCode.FAIL_MESSAGE
        print(e)
    return jsonify(result)


# 添加机器人
@admin_robot.get('/add')
@authorize("admin:robot:add")
def add():
    return render_template('admin/robot/add.html')


# 保存机器人
@admin_robot.post('/save')
@authorize("admin:robot:add", log=True)
def save():
    req_json = request.json
    name = str_escape(req_json.get('name'))
    code = str_escape(req_json.get('code'))
    remark = str_escape(req_json.get('remark'))
    if not name or not code:
        return fail_api(msg="名称编码不得为空")

    if bool(Robot_Info.query.filter_by(name=name).count()):
        return fail_api(msg="机器人已经存在")
    robot = Robot_Info(name=name, code=code, remark=remark)
    db.session.add(robot)
    db.session.commit()
    return success_api(msg="增加成功")


# 删除机器人
@admin_robot.delete('/remove/<int:id>')
@authorize("admin:robot:remove", log=True)
def robotDelete(id):
    res = Robot_Info.query.filter_by(id=id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


# 启用机器人
@admin_robot.put('/enable')
@authorize("admin:robot:add", log=True)
def enable():
    _id = request.json.get('id')
    if _id:
        res = enable_status(model=Robot_Info, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="启动成功")
    return fail_api(msg="数据错误")


# 启用机器人
@admin_robot.put('/disable')
@authorize("admin:robot:add", log=True)
def dis_enable():
    _id = request.json.get('id')
    if _id:
        res = disable_status(model=Robot_Info, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="禁用成功")
    return fail_api(msg="数据错误")
